package com.swotxu.oldwebproject.session;

import com.swotxu.oldwebproject.redis.connection.IRedisConnection;
import com.swotxu.oldwebproject.session.handler.RedisSessionHandler;
import com.swotxu.oldwebproject.session.http.RedisSessionRequestWrapper;
import com.swotxu.oldwebproject.session.utils.RedisSessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

/**
 * redissession 操作类
 * 用于生成redissession对象
 *
 * @Date: 2020/1/9 18:21
 * @Author: xu.hai
 */
public class RedisSessionRepository {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisSessionRequestWrapper.class);

    private IRedisConnection redisConnection;

    public RedisSessionRepository(IRedisConnection redisConnection) {
        this.redisConnection = redisConnection;
    }

    /**
     * 优先校验，redis是否存在此 session，
     * 若存在，返回指定session，否则，根据参数判断是否新建 session
     *
     * @param token
     * @param servletContext
     * @param create
     * @return
     */
    public HttpSession getSession(String token, ServletContext servletContext, boolean create) {
        String key = RedisSessionUtil.getSessionKey(token);
        LOGGER.debug("key: {}, create: {}", key, create);

        if(redisConnection.exists(key)){
            return existSession(token, servletContext);
        }
        return create? newSession(token, servletContext) : null;

    }
    private HttpSession existSession(String token, ServletContext servletContext) {
        RedisSession session = RedisSession.createExistSession(token, servletContext, redisConnection);
        return RedisSessionHandler.getInstance(session);
    }

    private HttpSession newSession(String token, ServletContext servletContext) {
        RedisSession session = RedisSession.createNewSession(token, servletContext, redisConnection);
        return RedisSessionHandler.getInstance(session);
    }
}
